<template>
	<view class="body-view">
		<!--导航和状态栏-->
		<view class="state-navigation">
			<view class="slim_header_navigation d-flex a-center j-center" >
				<view class="left_box" @tap="goBack">
					<image src="/static/center/back.png" class="back"></image>
				</view>
				<view>
					<view class="title">运动打卡</view>
					<view class="group-name">{{groupInfo?.name}}</view>
				</view>
				<view class="right_box">
					<!-- <image src="/static/center/dian.png" class="dian"></image> -->
				</view>
			</view>
		</view>
		<!-- 顶部位置占位 -->
		<view style="height:calc(100rpx + var(--status-bar-height));"></view>
		<view class="top-search d-flex a-center j-between">
			<view class="search-input d-flex a-center">
				<view class="input-icon">
					<i class="tmicon tmicon-search" style="color:#cccccc;font-size:36rpx;"></i>
				</view>
				<view class="input-input">搜索运动</view>
			</view>
			<view class="search-date d-flex a-center j-center" @tap="showDateTable">
				<view class="date-content">{{moment(selectDate).format("M月D日")}}<br>{{moment(selectDate).locale('zh-cn').format('dddd')}}</view>
				<image class="date-drop" src="@/static/image/drop-down.png"></image>
			</view>
		</view>
		<view class="classification d-flex">
			<view class="left-class heights">
				<view v-for="(item,index) in pageData" class="class-cell d-flex a-center j-center">
					<view @tap="chooseClass(index)" :class="`${selectClass==index?'class-cell-true':'class-cell-false'}`">
						<template v-if="item.code=='8888888'">
							<i class="icon icon-wodefangan" :style="{fontSize: '34rpx',color:selectClass==index?'#ffffff':'#FFAF67'}"></i>
						</template>
						<template v-else>{{classIcon[item.code]}}{{item.name}}</template>
					</view>
				</view>
			</view>
			<view class="right-class heights">
				<scroll-view v-for="(item,index) in pageData" v-show="index==selectClass" scroll-y="true" class="heights">
					<template v-if="item.code=='9999999'">
						<view class="class-row-title">收藏{{item?.childNode?.filter((node:any) => node.note == 0).length==0?'（暂无）':''}}</view>
						<template v-for="items in item?.childNode" :key="items.id">
							<view v-if="items.note==0" class="class-row d-flex">
								<view class="class-row-icon">
									<image v-if="items.heatLevel=='1'" class="row-fire" src="@/static/image/fire-3.png"></image>
									<image v-if="items.heatLevel=='2'" class="row-fire" src="@/static/image/fire-2.png"></image>
									<image v-if="items.heatLevel=='3'" class="row-fire" src="@/static/image/fire-1.png"></image>
								</view>
								<view  class="class-row-content"  @tap="showAddCart(items)">
									<view class="row-name">{{items.name}}</view>
									<view class="row-consume">{{items.heat}}千卡/{{items.time}}分钟</view>
								</view>
								<view class="class-row-check d-flex a-center j-end"  @tap="onCheck(items)">
									<image v-if="items.isCheck" class="row-check" src="@/static/image/sports-menu-check-true.png"></image>
									<image v-else class="row-check" src="@/static/image/sports-menu-check-false.png"></image>
								</view>
							</view>
						</template>
						<view class="class-row-title">常用{{item?.childNode?.filter((node:any) => node.note == 1).length==0?'（暂无）':''}}</view>
						<template v-for="items in item?.childNode" :key="items.id">
							<view v-if="items.note==1" class="class-row d-flex">
								<view class="class-row-icon">
									<image v-if="items.heatLevel=='1'" class="row-fire" src="@/static/image/fire-3.png"></image>
									<image v-if="items.heatLevel=='2'" class="row-fire" src="@/static/image/fire-2.png"></image>
									<image v-if="items.heatLevel=='3'" class="row-fire" src="@/static/image/fire-1.png"></image>
								</view>
								<view  class="class-row-content"  @tap="showAddCart(items)">
									<view class="row-name">{{items.name}}</view>
									<view class="row-consume">{{items.heat}}千卡/{{items.time}}分钟</view>
								</view>
								<view class="class-row-check d-flex a-center j-end" @tap="onCheck(items)">
									<image v-if="items.isCheck" class="row-check" src="@/static/image/sports-menu-check-true.png"></image>
									<image v-else class="row-check" src="@/static/image/sports-menu-check-false.png"></image>
								</view>
							</view>
						</template>
					</template>
					<template v-else>
						<view v-for="items in item?.childNode" class="class-row d-flex" >
							<view class="class-row-icon">
								<image v-if="items.heatLevel=='1'" class="row-fire" src="@/static/image/fire-3.png"></image>
								<image v-if="items.heatLevel=='2'" class="row-fire" src="@/static/image/fire-2.png"></image>
								<image v-if="items.heatLevel=='3'" class="row-fire" src="@/static/image/fire-1.png"></image>
							</view>
							<view  class="class-row-content" @tap="showAddCart(items)">
								<view class="row-name">{{items.name}}</view>
								<view class="row-consume">{{items.heat}}千卡/{{items.time}}分钟</view>
							</view>
							<view class="class-row-check d-flex a-center j-end" @tap="onCheck(items)">
								<image v-if="items.isCheck" class="row-check" src="@/static/image/sports-menu-check-true.png"></image>
								<image v-else class="row-check" src="@/static/image/sports-menu-check-false.png"></image>
							</view>
						</view>
					</template>
				</scroll-view>
			</view>
		</view>
		<view class="sports-add d-flex a-center j-center">
			<view @tap="showAddCustom" class="d-flex a-center j-center">
				<view class="add-icon d-flex a-center j-center" :style="{background: addDisable?'#ABABAB':'#FFAF67' }">
					<i class="icon icon-a-" style="color:#ffffff;font-size:36rpx;"></i>
				</view>
				<view class="add-text">添加自定义运动</view>
			</view>
		</view>
		<view class="sports-button d-flex j-between">
			<view class="d-flex" @tap="showCheck">
				<uni-badge :text="sportsCart.length" absolute="rightTop" :offset="[7, 7]" :custom-style="{backgroundColor:'#FF5831'}" size="normal">
					<image class="button-cart" src="@/static/image/sports-menu-cart.png"></image>
				</uni-badge>
				<view v-if="sportsCart.length>0" class="button-text">共{{sportsCart.length}}项运动({{cartHeat}}千卡)</view>
				<view v-else class="button-text">还未添加</view>
			</view>
				<tm-button :disabled="addDisable"  _style="margin-top: -6rpx;font-weight: 600;" round="5" :width="260" :height="80" :shadow="-1"
				    color="#FFAF67" disabled-color="#ABABAB" :fontSize="32" fontColor="#ffffff" @tap="submit"
				    label="打卡"></tm-button>
		</view>
		<!--阴影层-->
		<view class="sports-shadow"></view>
		<!--购物车-->
		<uni-popup ref="checkPopup" :safe-area="false" type="bottom" style="z-index: 85;">
			<view class="checkPopup">
				<scroll-view scroll-y="true" style="max-height: 700rpx;">
					<view v-for="item in sportsCart" class="checkPopup-row d-flex j-end">
						<view class="checkPopup-row-cell d-flex a-center">
							<image v-if="item.heatLevel=='1'" class="checkPopup-row-fire" src="@/static/image/fire-3.png"></image>
							<image v-if="item.heatLevel=='2'" class="checkPopup-row-fire" src="@/static/image/fire-2.png"></image>
							<image v-if="item.heatLevel=='3'" class="checkPopup-row-fire" src="@/static/image/fire-1.png"></image>
							<view class="checkPopup-row-name">{{item.name}}</view>
						</view>
						<view class="checkPopup-row-content d-flex a-center j-end">
							<view class="checkPopup-row-time">{{item.time}}{{item.unitUnit}}</view>
							<image v-if="!addDisable" @tap="showEdit(item)" class="checkPopup-row-edit" src="@/static/image/checkPopup-edit.png"></image>
						</view>
						<view class="checkPopup-row-button d-flex a-center j-end">
							<view class="checkPopup-row-calorie">{{item.heat}}千卡</view>
							<image v-if="!addDisable" @tap="delCheck(item)" class="checkPopup-row-del" src="@/static/image/checkPopup-del.png"></image>
						</view>
					</view>
				</scroll-view>
				<view :class="`checkPopup-upload d-flex ${imageUrlList.length==0?'j-center':''}`">
					<view class="checkPopup-upload-image" v-for="(item,index) in imageUrlList">
						<image @tap="previewImage('preview',index,imageUrlList)" :id="`preview${index}`" mode="aspectFill" class="upload-image-img" :src="item"></image>
						<view class="upload-image-del d-flex a-center j-center">
							<image @tap="delImage(index)" class="image-del-icon" src="@/static/image/upload-image-del.png"></image>
						</view>
					</view>
					<view v-if="imageUrlList.length<4&&!addDisable" class="upload-cell-button" @tap="imageUpload">
						<image class="cell-content-icon" src="@/static/image/checkPopup-camera.png"></image>
						<view class="cell-content-text">上传照片</view>
					</view>
				</view>
			</view>
		</uni-popup>
		<!--删除控件-->
		<uni-popup ref="popup" :safe-area="false">
		    <view class="sys-confirm-content">
				<view class="confirm-content-title">取消{{delRow.name}}吗？</view>
				<view  @tap="delChoose" class="content-button button-confirm" style="color: #FD5745;">删除</view>
				<view style="height: 20rpx; background: #f5f5f5"></view>
				<view @tap="closePopup" class="content-button" style="color: #999999;">取消</view>
		    </view>
		</uni-popup>
		<!--
		<uni-popup ref="popup" background-color="#fff">
		    <view class="popup-content">
		        <view class="desp d-flex a-center">取消{{delRow.name}}吗？</view>
		        <view
		            class="row d-flex a-center j-center error"
		            @tap="delChoose"
		            >删除</view
		        >
		        <view style="height: 20rpx; background: #f5f5f5"></view>
		        <view
		            class="row d-flex a-center j-center cancel"
		            @tap="closePopup"
		            >取消</view
		        >
		    </view>
		</uni-popup>
		-->
		<!--日期选择-->
		<dateTable 
			ref="datePopup"
			:markDate="markDate"
			:initialDate="selectDate"
			color="#FFAF67"
			minDate="2023-1-1"
			:maxDate="moment().format('YYYY-MM-DD')"
			@onGetDate="onGetDate"
			@changeMoon="onChangeMoon">
		</dateTable>
		<!--运动编辑-->
		<uni-popup ref="editPopup" :safe-area="false" type="bottom" @change="editChange">
			<view class="popup-edit">
				<view class="edit-name d-flex a-center">
					<!--
					<view class="edit-name-icon"></view>
					-->
					<image v-if="editSports.heatLevel=='1'" style="width: 30rpx;height: 30rpx;" src="@/static/image/fire-3.png"></image>
					<image v-if="editSports.heatLevel=='2'" style="width: 30rpx;height: 30rpx;" src="@/static/image/fire-2.png"></image>
					<image v-if="editSports.heatLevel=='3'" style="width: 30rpx;height: 30rpx;" src="@/static/image/fire-1.png"></image>
					
					<view class="edit-name-content">
						<view class="edit-name-text">{{editSports.name}}</view>
						<view class="edit-name-describe">{{editSports.heat}}千卡/{{editSports.time}}{{editSports.unitUnit}}</view>
					</view>
					<view class="edit-collect d-flex a-center j-end">
						<view class="d-flex a-center" @tap="onCollect" >
							<image class="edit-collect-icom" v-if="editSports.isCollect" src="@/static/image/sports-collect-yes.png"></image>
							<image class="edit-collect-icom" v-else src="@/static/image/sports-collect-no.png"></image>
							<text class="edit-collect-text">收藏</text>
						</view>
					</view>
				</view>
				<view class="edit-input">
					<view class="edit-input-time d-flex">
						<view class="input-time-text">{{editTime}}</view>
						<view class="input-time-unit">分钟</view>
					</view>
					<view class="edit-input-describe">热量约{{editHeat}}千卡</view>
				</view>
				<view class="edit-keyboard d-flex j-between wrap">
					<view @touchstart="count('1')" class="edit-keyboard-button">1</view>
					<view @touchstart="count('2')" class="edit-keyboard-button">2</view>
					<view @touchstart="count('3')" class="edit-keyboard-button">3</view>
					<view @touchstart="count('4')" class="edit-keyboard-button">4</view>
					<view @touchstart="count('5')" class="edit-keyboard-button">5</view>
					<view @touchstart="count('6')" class="edit-keyboard-button">6</view>
					<view @touchstart="count('7')" class="edit-keyboard-button">7</view>
					<view @touchstart="count('8')" class="edit-keyboard-button">8</view>
					<view @touchstart="count('9')" class="edit-keyboard-button">9</view>
					<view style="width: 210rpx;"></view>
					<view @touchstart="count('0')" class="edit-keyboard-button">0</view>
					<view @touchstart="count('del')" class="edit-keyboard-button d-flex a-center j-center">
						<image class="keyboard-button-image" src="@/static/image/keyboard-del.png"></image>
					</view>
				</view>
				<view class="confirm-button d-flex j-center">
					<tm-button _style="margin-top: -6rpx;font-weight: 600;" round="5" :width="690" :height="80" :shadow="-1"
					    :linear-color="['#FFAF67', '#E48E41']" linear="left" :fontSize="32" fontColor="#ffffff" @tap="addCart"
					    label="确定"></tm-button>
				</view>
			</view>
		</uni-popup>
		<!--自定义运动添加-->
		<uni-popup ref="addPopup" :safe-area="false" type="bottom">
			<view class="popup-add" :style="{transform: 'translateY(-'+ keyBoardHeight +'px)'}">
				<viue class="popup-title d-flex a-center j-center">
					<view class="title-text">添加自定义运动</view>
					<image @tap="addPopup.close()" class="title-icon" src="@/static/image/close.png"></image>
				</viue>
				<view class="form-add">
					<uni-forms ref="addForm" err-show-type="toast" :modelValue="addFormData" :rules="addRules">
						<uni-forms-item name="name">
							<view class="forms-item d-flex a-center">
								<view class="forms-item-label">运动名</view>
								<input :adjust-position="false" class="forms-item-input" v-model="addFormData.name"/>
							</view>
						</uni-forms-item>
						<uni-forms-item name="unit">
							<view class="forms-item d-flex a-center">
								<view class="forms-item-label">单位</view>
								<input :adjust-position="false" type="number" class="forms-item-input" v-model="addFormData.unit" style="width: 227rpx;"/>
								<view class="add-radio d-flex">
									<view @tap="addFormData.unitUnit='分钟'" :class="`add-radio-cell ${addFormData.unitUnit=='分钟'?'add-radio-yes':''}`">分钟</view>
									<view @tap="addFormData.unitUnit='次'" :class="`add-radio-cell ${addFormData.unitUnit=='次'?'add-radio-yes':''}`">次</view>
									<view @tap="addFormData.unitUnit='千米'" :class="`add-radio-cell ${addFormData.unitUnit=='千米'?'add-radio-yes':''}`">千米</view>
								</view>
							</view>
						</uni-forms-item>
						<uni-forms-item name="heat">
							<view class="forms-item d-flex a-center">
								<view class="forms-item-label">总热量</view>
								<input :adjust-position="false" type="number" class="forms-item-input" v-model="addFormData.heat" style="width: 227rpx;"/>
								<view class="add-radio d-flex">
									<view @tap="editHeatUnit('千卡')" style="width: 170rpx;" :class="`add-radio-cell ${addFormData.heatUnit=='千卡'?'add-radio-yes':''}`">千卡</view>
									<view @tap="editHeatUnit('千焦')" style="width: 170rpx;" :class="`add-radio-cell ${addFormData.heatUnit=='千焦'?'add-radio-yes':''}`">千焦</view>
								</view>
							</view>
							<view class="forms-item-describe">
								{{addFormData.heatUnit=='千焦'?`最终记录时将换算成千卡，当前${heatConvert(addFormData.heat)}千卡`:''}}
							</view>
						</uni-forms-item>
					</uni-forms>
				</view>
				<view class="confirm-button d-flex j-center">
					<view class="confirm-describe"></view>
					<tm-button _style="margin-top: -6rpx;font-weight: 600;" round="5" :width="690" :height="80" :shadow="-1"
					    :linear-color="['#FFAF67', '#E48E41']" linear="left" :fontSize="32" fontColor="#ffffff" @tap="addEditCustom"
					    label="确定"></tm-button>
				</view>
			</view>
		</uni-popup>
		<imagePreview ref="preview" @onChange="imageChange"></imagePreview>
	</view>
</template>

<script setup lang="tsx" name="sportsGroupMenu">
import { 
			getSportsList,//查询运动列表
			editSportsCollect,//运动收藏
			addOrUpdateGroupSports,//添加或编辑运动
			userSportsRecord,//查询用户运动记录
			getGroupSportsDate,//查询用户有运动的日期
			getFavoritesSports,//获取运动收藏列表
			getCircleDetail//查询群信息
		} from "@/api/api";
import { onLoad,onShow,onHide } from '@dcloudio/uni-app';
import { ref,nextTick } from 'vue';
import { userData as userDataStore } from "@/store/userData";
import { BASE_URL } from "@/api/request";
import {showLoading,closeLoading} from '@/utils/utils';
import dateTable from "@/components/dateTable.vue";
import moment from "moment";
import "moment/dist/locale/zh-cn";
import BigNumber from "bignumber.js";
import imagePreview from "@/components/imagePreview.vue";
import { getHDImages } from '@/utils/format';
import { chooseImage } from "@/utils/utils";

const keyBoardHeight = ref(0);
const goBack = () => {
	uni.navigateBack();
};
//const classIcon:any = ref(["","","🚶","🏃‍♀","🚴‍♀️","🤸","🧘‍♀","🏊‍♀️","⚽️","💪"])
const classIcon:any = ref({
	'1000':'🚶',
	'1100':'🏃‍♀',
	'1200':'🚴‍♀',
	'1300':'🤸',
	'1400':'🧘‍♀',
	'1500':'🏊‍♀',
	'1600':'⚽',
	'1700':'💪',
});
const pageData:any = ref();
const userData: any = userDataStore();
const selectClass = ref(1)//选中的分类
const selectDate:any = ref(new Date());//选择的日期
const groupId = ref();//群ID
const groupInfo = ref();//群信息
let isLoad = false;//判断是否为首次进入
onLoad((options:any) => {
	isLoad = true;
	groupId.value = options.groupId;
	if(options.recordDate!=null)selectDate.value = options.recordDate;
	isAddDisable();//设置按钮是否可用
	loadPageData();
	getCircleDetail({groupId:groupId.value}).then((res:any) => {
		if(res.success){
			groupInfo.value = res.data;
		}
	});
});
onShow(() => {
	//处理键盘盖住文本框问题
	/* #ifndef H5 */
	uni.onKeyboardHeightChange(res => {
		keyBoardHeight.value = res.height;
	})
	/*#endif*/
});
onHide(() => {
	/* #ifndef H5 */
	uni.offKeyboardHeightChange(); 
	/*#endif*/
});
//单位换算
const editHeatUnit = (unit:string) => {
	addFormData.value.heatUnit = unit;
	if(addFormData.value.isEdit){
		if(unit == "千焦"){
			let i = Math.round(new BigNumber(addFormData.value.heat).div(new BigNumber(0.2389)).toNumber());
			if(isNaN(i))i=0;
			addFormData.value.heat = i 
			addFormData.value.foodHeat = i 
		}
		if(unit == "千卡"){
			let i = Math.round(new BigNumber(addFormData.value.heat).times(new BigNumber(0.2389)).toNumber());
			if(isNaN(i))i=0;
			addFormData.value.heat = i
			addFormData.value.foodHeat = i 
		}
	}
}
const loadPageData = () => {
	getSportsList({userId:userData.id}).then((res:any) => {
		if(res.success){
			let collectList = res.data.filter((item:any) => item.code=="9999999")[0].childNode.filter((node:any) => node.note == 0);
			res.data.forEach((item:any) => {
				item?.childNode.forEach((items:any) => {
					items.isCheck = false;//是否选中
					items.isCollect = false;//是否收藏
					let i = collectList.filter((node:any) => node.code == items.code);
					if(i.length>0)items.isCollect = true;
				})
			})
			pageData.value = res.data;
			selectClass.value = pageData.value.findIndex((item:any) => item.code=="9999999");
			getSportsRecord();//加载记录
		}
		
	});
}
const chooseClass = (index:number) =>{
	selectClass.value = index;
}
//弹出选中框
const checkPopup = ref();
const showCheck =  () => {
	if(sportsCart.value.length === 0)return;
	if(!checkPopup.value.showPopup){
		checkPopup.value.open()
	}else{
		checkPopup.value.close()
	}
}
//图片预览
const preview = ref();
const previewImage = (id:string,index:number,urls:any) => {
	uni.createSelectorQuery().select(`#${id}${index}`).boundingClientRect().exec((ret)=>{
		//e.callback(ret[0])
		let params = {
			startInfo:[ret[0]],//图片的初始大小与位置
			idPre:id,
			index:index,//当前图片地址
			urls:getHDImages(urls),//预览集合图片地址
		}
		preview.value.open(params);
	});
}
const imageChange = (e:any) => {
	try{
		uni.createSelectorQuery().select(`#${e.id}${e.index}`).boundingClientRect().exec((ret)=>{
			uni.$emit("imagePreviewUpdate",ret[0])
		});
	}catch(e){
		uni.$emit("imagePreviewUpdate",null)
	}
}
//图片上传
const imageUrlList:any = ref([])
const imageUpload = () => {
	chooseImage({
		count:1,
	    success: (chooseImageRes) => {
	        const token = uni.getStorageSync("api_token");
	        const tempFilePaths = chooseImageRes.tempFilePaths;
	        showLoading();
	        uni.uploadFile({
	            header: {
	                token,
	            },
	            url: `${BASE_URL}/file/upload`, //仅为示例，非真实的接口地址
	            filePath: tempFilePaths[0],
	            name: "file",
	            formData: {
                    'isCompress':1,
                },
	            success: (uploadFileRes) => {
	                let res: any;
	                 closeLoading();
	                try {
	                    res = JSON.parse(uploadFileRes.data);
	                } catch (error) {
	                    uni.showToast({
	                        icon: "none",
	                        title: '请稍后再试',
	                        duration: 1500,
	                    });
	                    return;
	                }
	                const { flag, data } = res;
	                if (flag !== 1) {
	                    uni.showToast({
	                        icon: "none",
	                        title: '上传失败,请稍后再试',
	                        duration: 1500,
	                    });
	                    return;
	                }
	                const { fileUrl } = data;
	                imageUrlList.value.push(fileUrl);
	            },
	            fail() {
	                closeLoading();
	                uni.showToast({
	                    icon: "none",
	                    title: '上传失败,请稍后再试',
	                    duration: 1500,
	                });
	            },
	        });
	    },
	});
}
const delImage = (index:number) => {
	imageUrlList.value.splice(index, 1);
}
const datePopup = ref();
const markDate:any = ref([])//需要标识的日期
const showDateTable = () => {
	onChangeMoon(selectDate.value);//查询需要高亮显示的日期
	datePopup.value.open()
}
//日期选择
const onGetDate = (date:any) => {
	selectDate.value = date;
	getSportsRecord();//查询用户运动记录
	isAddDisable();//设置按钮是否可用
}
//显示编辑页面
const sportsCart:any = ref([]);//运动购物车
const cartHeat = ref(0);//购物车总热量
	
const editPopup = ref();
const editSports = ref();
const editTime = ref();//编辑输入的时间
const editHeat = ref();//编辑计算的热量

const countCartHeat = () => {
	cartHeat.value = 0;
	sportsCart.value.forEach((item:any) => {
		cartHeat.value += Number(item.heat);
	});
}
//设置选中状态
const setSelect = () => {
	pageData.value.forEach((item:any) => {
		item?.childNode.forEach((items:any) => {
			items.isCheck = false;
			for(let i=0;i<sportsCart.value.length;i++){
				if(item.code == "6666666"){
					if(items.name == sportsCart.value[i].name){
						items.isCheck = true;
						break;
					}
				}else{
					if(items.code == sportsCart.value[i].code){
						items.isCheck = true;
						break;
					}
				}
				/*
				if(items.code === sportsCart.value[i].code){
					items.isCheck = true;
					break;
				}
				*/
			}
		})
	})
}
//判断是否收藏
const isCollect = (sports:any) => {
	//收藏列表
	let collectList = pageData.value[0].childNode;
	let result = collectList.filter((item:any) => item.code === sports.code);
	if(result.length>0)
		return true;
	else
		return false;
}
const showAddCart = (sports:any) => {
	if(addDisable.value)return;
	if(sports.code==null){
		if(sports.isCheck){
			for(let i=0;i<sportsCart.value.length;i++){
				if(sports.name === sportsCart.value[i].name){
					addFormData.value = sportsCart.value[i];
					addFormData.value.heatUnit = "千卡"
					break;
				}
			}
		}else{
			addFormData.value = {
				name:sports.name,
				unit:sports.unitNumber,
				unitUnit:"分钟",
				heat:sports.heat,
				heatLevel:2,
				heatUnit:"千卡",
				addType:1//用户自定义添加
			}
		}
		addPopup.value.open();
	}else{
		editPopup.value.open();
		if(sports.isCheck){
			for(let i=0;i<sportsCart.value.length;i++){
				if(sports.code === sportsCart.value[i].code){
					editSports.value = sportsCart.value[i];
					
					editSports.value.isCollect = isCollect(editSports.value);
					editSports.value.isCheck = true;
					break;
				}
			}
		}else{
			let param = JSON.parse(JSON.stringify(sports));
			param.addType = 0;//0系统添加，1自定义
			param.unitUnit = "分钟"
			editSports.value = param;
		}
		editTime.value = editSports.value.time.toString();
		editHeat.value = editSports.value.heat;
	}
}
//加入购物车或确认修改
const addCart = () => {
	if(editTime.value==null||editTime.value==""||editTime.value==0){
		uni.showToast({
		    icon: "none",
		    title: '请输入时间',
		    duration: 1500,
		});
		return
	}
	editSports.value.time = editTime.value;
	editSports.value.heat = editHeat.value;
	editPopup.value.close();
	
	let result = sportsCart.value.filter((item:any) => item.code === editSports.value.code);
	if(result.length === 0){
		sportsCart.value.push(editSports.value)
	}else{
		for(let i=0;i<sportsCart.value.length;i++){
			if(sportsCart.value[i].code==editSports.value.code){
				sportsCart.value[i]=editSports.value;
				break;
			}
		}
	};
	countCartHeat();//已选择的总热量
	setSelect();//
}
//删除购物车中项目
const delCheck = (obj:any) => {
	let idx = sportsCart.value.indexOf(obj);
	if (idx !== -1){
		sportsCart.value.splice(idx, 1);
		setSelect();
	}
	if(sportsCart.value.length==0)checkPopup.value.close();
}
const popup = ref();
const delRow = ref();
const onCheck = (row:any) => {
	if(addDisable.value)return;
	if(row.isCheck){
		if(row.code==null){
			let sportsCartObj = sportsCart.value.filter((item:any) => item.addType == 1 && row.name == item.name);
			delRow.value = sportsCartObj[0]
		}else{
			let sportsCartObj = sportsCart.value.filter((item:any) => item.addType == 0 && row.code == item.code);
			delRow.value = sportsCartObj[0]
		}
		//delRow.value = row;
		openPopup();
	}else{
		showAddCart(row);
	}
}
const openPopup = () => {
    popup.value.open("bottom");
};

const closePopup = () => {
    popup.value.close();
};
const delChoose = () => {
	//let idx = sportsCart.value.findIndex((item:any) => item.code === delRow.value.code);
	let idx = -1;
	if(delRow.value.addType==1){
	idx = sportsCart.value.findIndex((item:any) => item.addType==1 && item.name === delRow.value.name);
	}
	if(delRow.value.addType==0){
	idx = sportsCart.value.findIndex((item:any) => item.addType==0 && item.code === delRow.value.code);
	}
	if (idx !== -1){
		sportsCart.value.splice(idx, 1);
		countCartHeat();
		setSelect();
	}
	popup.value.close();
}
const onCollect = () => {
	let params = {
		userId:userData.id,
		code:editSports.value.code,
		optType:!editSports.value.isCollect
	}
	editSportsCollect(params).then((res:any) => {
		if(res.success){
			let title = " 已收藏";
			if(!params.optType) title = " 已取消收藏";
			uni.showToast({
			    title: title,  
			    icon: 'none',  
			    duration: 1500,
			});
			editSports.value.isCollect = params.optType;
		}else{
			uni.showToast({
			    title: res.message,  
			    icon: 'none',  
			    duration: 1500,
			});
		}
	})
}
const count = (str:string) => {
	if(str!=="del"){
		if(str==="."){
			if(editTime.value.indexOf(".")===-1)editTime.value += str
		}else{
			let a = editTime.value + str;
			if(Number(a)>999){
				uni.showToast({
				    icon: "none",
				    title: '最大数999',
				    duration: 1500,
				});
			}else{
				editTime.value += str
			}
		}
	}else{
		editTime.value = editTime.value.slice(0, -1);
	}
	//第一位是0则去掉0
	if(editTime.value.indexOf(".")===-1&&editTime.value.length===2&&editTime.value.indexOf("0")===0){
		editTime.value = editTime.value.slice(1);
	}
	//热量计算
	if(editTime.value==""){
		editHeat.value = 0;
	}else{
		let cardinal = new BigNumber(editSports.value.heat).div(new BigNumber(editSports.value.time));
		editHeat.value = cardinal.times(new BigNumber(editTime.value)).toNumber().toFixed()
	}
}

//添加自定义运动相关功能
const addPopup = ref();
const addFormData = ref();
const showAddCustom = () => {
	if(addDisable.value)return;
	let code = Math.floor(Date.now() * Math.random()).toString();
	addFormData.value = {
		code:code,
		name:"",
		unit:"",
		unitUnit:"分钟",
		heat:"",
		heatLevel:2,
		heatUnit:"千卡",
		addType:1//用户自定义添加
	}
	addPopup.value.open();
}
const addRules: any = ref({
	name: {
		rules: [{
				required: true,
				errorMessage: "请输入名称",
			},
			{
				minLength: 2,
				maxLength: 20,
				errorMessage: '名称长度在 {minLength} 到 {maxLength} 个字符',
			}
		]
	},
	unit: {
		rules: [{
				required: true,
				errorMessage: "请输入单位",
			},
			{
				format:"number",
				errorMessage: "单位必须是数字",
			},
			{
				pattern: /^\d+$/,
				errorMessage: "单位必须是整数",
			},
			{
				minimum: 1,
				errorMessage: "单位最小值是1",
			}
		]
	},
	heat: {
		rules: [{
				required: true,
				errorMessage: "请输入总热量",
			},
			{
				pattern: /^\d+$/,
				errorMessage: "总热量必须是整数",
			},
			{
				format:"number",
				errorMessage: "总热量必须是数字",
			},
			{
				minimum: 5,
				errorMessage: "总热量最小值是5",
			}
		]
	}
})
const addForm = ref()
//添加修改自定义运动
const addEditCustom = () => {
	addForm.value.validate().then(()=>{
		if(addFormData.value.heatUnit=="千焦"){
			addFormData.value.heat = heatConvert(addFormData.value.heat);
			addFormData.value.heatUnit = "千卡";
		}
		addFormData.value.time = addFormData.value.unit;
		
		let result = sportsCart.value.filter((item:any) => item.addType == 1 && item.name === addFormData.value.name);
		if(result.length === 0){
			sportsCart.value.push(addFormData.value)
		}else{
			for(let i=0;i<sportsCart.value.length;i++){
				if(sportsCart.value[i].name==addFormData.value.name){
					sportsCart.value[i]=addFormData.value;
					break;
				}
			}
		};
		addPopup.value.close();
		countCartHeat();
		setSelect();
	}).catch((err: any) =>{
		console.log('表单错误信息：', err);
	})
}
//热量单位转换
const heatConvert = (heat:number) => {
	let i = Math.round(new BigNumber(heat).times(new BigNumber(0.2389)).toNumber());
	if(isNaN(i))i=0;
	return i;
}
const showEdit = (sports:any) => {
	if(sports.addType === 0){
		editSports.value = sports;
		editPopup.value.open();
		editTime.value = editSports.value.time.toString();
		editHeat.value = editSports.value.heat;
	}
	if(sports.addType === 1){
		addFormData.value = sports;
		addFormData.value.isEdit = true
		addPopup.value.open()
	}
}
const submit = () => {
	if(sportsCart.value.length==0){
		uni.showToast({
		    title: "请先选择运动！",  
		    icon: 'none',  
		    duration: 1500,
		});
		return;
	}
	let userSportsRecords:any = [];
	sportsCart.value.forEach((item:any) => {
		let code = item.code;
		if(item.addType===1) code = "";
		userSportsRecords.push({
			code:code,
			name:item.name,
			time:item.time,
			heat:item.heat,
			unit:item.unitUnit,
			heatLevel:item.heatLevel
		});
	})
	
	let param = {
		total:cartHeat.value,
		userId:userData.id,
		groupId:groupId.value,
		recordDate:moment(selectDate.value).format("YYYY-MM-DD"),
		img:imageUrlList.value.toString(),
		userSportsRecords:userSportsRecords
	}
	addOrUpdateGroupSports(param).then((res:any) => {
		if(res.success){
		   checkPopup.value.close();
		   uni.navigateBack({
		   	success:() => {
		   		uni.showToast({
		   		    title: "运动打卡成功",
		   		    icon: 'success', 
		   		    duration: 1500,
		   		});
		   	}
		   });
		}else{
			uni.showToast({
			    title: res.message,  
			    icon: 'none',  
			    duration: 1500,
			});
		}
	})
}
//查询用户运动记录
const getSportsRecord = () => {
	let param = {
		userId:userData.id,
		recordDate:moment(selectDate.value).format("YYYY-MM-DD"),
	}
	userSportsRecord(param).then((res:any) => {
		if(res.data.img!=null&&res.data.img!=""){
			let imgObj:any = [];
			let imgs = res.data.img.split(",");
			imgs.forEach((item:string) => {
				imgObj.push(item);
			})
			imageUrlList.value = imgObj;
		}
		let sportsCartData:any = [];
		res.data.userSportsRecords.forEach((item:any) => {
			let addType = 0;
			item.unitUnit = item.unit;
			if(item.code===""){
				addType = 1;
				item.unit = item.time;
			}
			item.addType = addType;
			sportsCartData.push(item);
		})
		sportsCart.value = sportsCartData;
		nextTick(() => {
			//首次加载购物车有数据，直接弹出
			if(isLoad){
				isLoad = false;
				if(sportsCart.value.length>0){
					checkPopup.value.open();
				}
			}
		})
		countCartHeat();
		setSelect();
	})
} 
//日期选择器月份变更时操作
const onChangeMoon = (date:any) => {
	markDate.value = [];
	let param = {
		userId:userData.id,
		groupId:groupId.value,
		recordDate:moment(date).format("YYYY-MM-DD"),
	}
	getGroupSportsDate(param).then((res:any) => {
		res.data.forEach((item:any) => {
			markDate.value.push(item.recordDate)
		})
	})
}

//判断添加按钮是否可用
const addDisable = ref(false);
const isAddDisable = () => {
	//设置多少天内可修改
	var threeDaysAgo = moment().subtract(3, 'days');  
	var today = moment();  
	
	var dateToCheck = moment(selectDate.value); // 这是你要检查的日期  
	  
	if (dateToCheck.isBetween(threeDaysAgo, today)) {  
		addDisable.value = false;
	} else {  
		addDisable.value =  true;
		uni.showToast({
		    title: "三天前记录仅可查看",  
		    icon: 'none',  
		    duration: 2000,
		});
	}
}
const editChange = (e:any) => {
	//关闭后刷新收藏页
	if(!e.show){
		getFavoritesSports({userId:userData.id}).then((res:any) => {
			let collectAndCommonList =  res.data.list;
			let collectList = collectAndCommonList.filter((node:any) => node.note == 0);
			collectAndCommonList.forEach((item:any) => {
				item.isCheck = false;//是否选中
				let result = sportsCart.value.filter((items:any) => items.code === item.code);
				if(result.length>0)item.isCheck = true;
				//是否收藏
				item.isCollect = false;
				let is = collectList.filter((items:any) => items.code === item.code);
				if(is.length>0){
					item.isCollect = true;//是否收藏
				}
			});
			pageData.value.filter((item:any) => item.code=="9999999")[0].childNode = collectAndCommonList;
			//pageData.value[0].childNode = collectAndCommonList;
			//设置收藏状态
			for(let i=1;i<pageData.value.length;i++){
				for(let j=0;j<pageData.value[i].childNode.length;j++){
					let obj = pageData.value[i].childNode[j];
					if(obj.code == editSports.value.code){
						obj.isCollect = editSports.value.isCollect;
					}
				}
			}
		});
	}
} 
</script>
<style lang="scss" scoped>
@import './sportsGroupMenu.scss';
</style>
